package com.jia.friends.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jia.constant.RedisConstant;
import com.jia.friends.constant.FollowRedisConstant;
import com.jia.friends.entity.Follow;
import com.jia.friends.mapper.FollowMapper;
import com.jia.friends.service.FollowService;
import com.jia.sms.entity.User;
import com.jia.sms.holder.UserHolder;
import com.jia.sms.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * (Follow)表服务实现类
 *
 * @author makejava
 * @since 2024-10-10 17:18:23
 */
@Service("followService")
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow>
        implements FollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserService userService;

    public static final String FOLLOW_REDIS_PREFIX = RedisConstant.PROJECT_REDIS_PREFIX
            + FollowRedisConstant.FRIEND_PREFIX;

    @Override
    public Boolean follow(Long followUserId, Boolean isFollow) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        String followKey = FOLLOW_REDIS_PREFIX + userId;
        // 判断是否关注
        if (isFollow) {
            // 关注 新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if (isSuccess) {
                stringRedisTemplate.opsForSet().add(followKey, String.valueOf(followUserId));
            }
        } else {
            // 取关 删除数据
            boolean isSuccess = remove(new QueryWrapper<Follow>().eq("user_id", userId)
                    .eq("follow_user_id", followUserId));
            if (isSuccess) {
                stringRedisTemplate.opsForSet().remove(followKey, String.valueOf(followUserId));
            }
        }
        return true;
    }

    @Override
    public Boolean isFollow(Long followUserId) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 查询是否关注
        Long count = query().eq("user_id", userId)
                .eq("follow_user_id", followUserId)
                .count();
        return count > 0;
    }

    @Override
    public List<User> commonFollow(Long userId) {
        // 当前用户
        Long id = UserHolder.getUser().getId();
        String sourceKey = FOLLOW_REDIS_PREFIX + id;
        // 目标用户
        String targetKey = FOLLOW_REDIS_PREFIX + userId;
        // 获取交集
        Set<String> ids = stringRedisTemplate.opsForSet().intersect(sourceKey, targetKey);
        // 查询交集用户数据
        return userService.listByIds(ids);
    }

}
